package com.free4inno.knowledgems.service;

import com.alibaba.fastjson.JSON;
import com.free4inno.knowledgems.dao.*;
import com.free4inno.knowledgems.domain.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * Author HUYUZHU.
 * Date 2021/3/27 23:06.
 */

@Slf4j
@Service
public class ResourceService {

    @Autowired
    private ResourceDAO resourceDao;

    @Autowired
    private UserDAO userDao;

    @Autowired
    private GroupInfoDAO groupInfoDao;

    @Autowired
    private LabelInfoDAO labelInfoDao;

    @Autowired
    private SpecResourceDAO specResourceDao;

    @Autowired
    private AttachmentDAO attachmentDao;

    @Autowired
    private UserGroupDAO userGroupDao;

    // 取群组名
    public String getGroupName(Resource resource) {
        log.info(this.getClass().getName() + "----in----" + "取资源群组名" + "----");
        String groupName = "";
        if (resource.getGroupId() != null && !resource.getGroupId().equals("")) {
            String[] group = resource.getGroupId().split(",|，");
            for (String s : group) {
                int groupId = (s == "" ? 0 : Integer.parseInt(s));
                GroupInfo groupInfo = groupInfoDao.findById(groupId).orElse(new GroupInfo());
                if (groupInfo.getGroupName() != null) {
                    String gn = groupInfo.getGroupName();
                    groupName = groupName + "," + gn;
                } else {
                    groupName = groupName + "," + "未知群组" + groupId;
                }
            }
            groupName = groupName.substring(1);
        } else {
            groupName = "该资源无群组";
        }
        log.info(this.getClass().getName() + "----out----" + "返回群组名" + "----");
        return groupName;
    }

    // 取标签名
    public String getLabelName(Resource resource) {
        log.info(this.getClass().getName() + "----in----" + "取资源标签名" + "----");
        String labelName = "";
        if (resource.getLabelId() != null && !resource.getLabelId().equals("")) {
            String[] label = resource.getLabelId().split(",|，");
            for (String s : label) {
                Integer labelId = (s.equals("") ? 0 : Integer.parseInt(s));
                LabelInfo labelInfo = labelInfoDao.findById(labelId).orElse(new LabelInfo());
                if (labelInfo.getLabelName() != null) {
                    String ln = labelInfo.getLabelName();
                    labelName = labelName + "," + ln;
                } else {
                    labelName = labelName + "," + "未知标签" + labelId;
                }
            }
            labelName = labelName.substring(1);
        } else {
            labelName = "该资源无标签";
        }
        log.info(this.getClass().getName() + "----out----" + "返回标签名" + "----");
        return labelName;
    }

    // 取附件
    public String getAttachmentJson(Integer resourceId) {
        log.info(this.getClass().getName() + "----in----" + "取资源附件" + "----");
        List<Attachment> attachmentList = attachmentDao.findAllByResourceId(resourceId);
        String attachmentJson = "[]";
        if (attachmentList != null && attachmentList.size() != 0) {
            int i = 0;
            ArrayList<Attachment> attachmentListNew = new ArrayList<>();
            for (Attachment attachment : attachmentList) {
                attachment.setId(i);
                attachmentListNew.add(attachment);
                i++;
            }
            attachmentJson = JSON.toJSONString(attachmentListNew);
        }
        log.info(this.getClass().getName() + "----out----" + "返回JSON格式的附件列表" + "----");
        return attachmentJson;
    }


    // 设置资源的推荐情况
    public void setRecommendResource(Resource resource) {
        log.info(this.getClass().getName() + "----in----" + "设置资源的推荐情况" + "----");
        Optional<SpecResource> recommendResource = specResourceDao.findByResourceIdAndType(resource.getId(), 1);
        if (recommendResource.isPresent()) {
            SpecResource specResource = recommendResource.get();
            Integer recommendType = specResource.getType();
            Integer recommendOrder = specResource.getOrder();
            resource.setRecommendType(recommendType);
            resource.setRecommendOrder(recommendOrder);
        }
        log.info(this.getClass().getName() + "----out----" + "完成资源推荐设置" + "----");
    }

    // 取资源的公告情况
    public void setAnnouncementResource(Resource resource) {
        log.info(this.getClass().getName() + "----in----" + "设置资源公告情况" + "----");
        Optional<SpecResource> announcementResource = specResourceDao.findByResourceIdAndType(resource.getId(), 2);
        if (announcementResource.isPresent()) {
            SpecResource announece = announcementResource.get();
            Integer noticeType = announece.getType();
            Integer noticeOrder = announece.getOrder();
            resource.setNoticeType(noticeType);
            resource.setNoticeOrder(noticeOrder);
        }
        log.info(this.getClass().getName() + "----out----" + "完成资源公告设置" + "----");
    }

    // 检查用户是否属于资源群组
    public boolean isInResourceGroup(Resource resource, int userId) {
        log.info(this.getClass().getName() + "----in----" + "检查用户是否属于资源群组" + "----");
        // 1. 判断资源自身群组配置
        if (resource.getGroupId() != null && resource.getGroupId().isEmpty()) {
            log.info(this.getClass().getName() + "----out----" + "该资源无群组配置，有权打开" + "----");
            return true;
        }
        // 2. 判断管理员身份
        User user = userDao.findById(userId).orElse(new User());
        if (user.getRoleId() == 1 || user.getRoleId() == 3) {
            log.info(this.getClass().getName() + "----out----" + "该用户为超级管理员/内容管理员，有权打开" + "----");
            return true;
        }
        // 3. 检查群组包含关系
        List<UserGroup> userGroups = userGroupDao.findByUserId(userId);
        String[] resourceGroups = resource.getGroupId().split(",");
        List<String> resourceGroupsList = Arrays.asList(resourceGroups);
        for (UserGroup userGroup : userGroups) {
            if (resourceGroupsList.contains(userGroup.getGroupId().toString())) {
                log.info(this.getClass().getName() + "----out----" + "用户属于当前资源群组，有权打开" + "----");
                return true;
            }
        }
        log.info(this.getClass().getName() + "----out----" + "用户不属于当前资源群组，无权打开" + "----");
        return false;
    }
}
